<script setup lang="ts">
import { ElTree } from 'element-plus'
import {
  Bottom,
  CirclePlus,
  Delete,
  Edit,
  Plus,
  Top,
} from '@element-plus/icons-vue'
import type { Tree } from './type'
import { usePoint, useTreeFilter } from './ViewTree'
import emitter from '@/bus'
import { dragEnergyUnit } from '@/api/modules/point'
import { cloneDeep } from 'lodash-es'

defineProps<{
  readonly?: boolean
}>()

const emits = defineEmits<{
  (e: 'nodeClick', o: Tree): void
}>()

const {
  treeData,
  vLoading,
  getTreeData,
  clickAppend,
  clickParentAppend,
  clickRemove,
  clickUpdate,
  clickMoveNext,
  clickMovePrev,
  prevable,
  nextable,
} = usePoint()

const treeRef = ref<InstanceType<typeof ElTree>>()
const { filterTextInput, filterNode } = useTreeFilter('pointName', (val: string) => {
  treeRef.value?.filter?.(val)
})

let copiedTreeData: any = null
const { $confirm, $message } = useCurrentInstance()

function clickNode(o: Tree) {
  emits('nodeClick', o)
  emitter.emit('click:point-tree-node', o)
}

function handleNodeDragStart() {
  copiedTreeData = cloneDeep(treeData.value)
}

async function handleNodeDrag(
  current: any,
  target: any,
  pos: 'before' | 'after' | 'inner',
) {
  const res = await $confirm(
    `是否确认将【${current.label}】拖到【${target.label}】【${({ before: '上方', after: '下方', inner: '子集' })[pos]}】`,
    '确认提示',
  ).catch(() => {
    treeData.value = copiedTreeData
    $message.info('取消拖动')
  })
  if (res === 'confirm') {
    const id = current?.data?.id
    const targetId = target?.data?.id
    if (id && targetId) {
      try {
        await dragEnergyUnit(id, targetId, pos)
        ElMessage.success('移动成功')
      }
      finally {
        await getTreeData()
      }
    }
  }
}

onMounted(async () => {
  await getTreeData()
  const first = treeData.value[0]
  if (first) {
    clickNode(first)
    treeRef.value?.setCurrentNode(first)
  }
})
</script>

<template>
  <div v-loading class="view-tree height-fill box-border" style="--container-left-width: 340px;">
    <h5 class="flex-incompressible margin-0 align-center flex justify-between">
      <span>用能单元（点位）</span>
      <TdButton
        v-if="!readonly" title="添加用能单元" :icon="CirclePlus" :disabled="!$power('add')" type="primary"
        class="fs-18" @click="clickParentAppend"
      />
    </h5>
    <ElInput v-model="filterTextInput" placeholder="关键字" class="flex-incompressible" />
    <ElScrollbar>
      <ElTree
        ref="treeRef" class="flex-fillRemaining" :data="treeData" :props="{
          label: 'pointName',
          children: 'children',
        }" node-key="id" highlight-current default-expand-all :expand-on-click-node="false"
        :filter-node-method="filterNode" draggable @contextmenu.prevent @node-click="clickNode"
        @node-drop="handleNodeDrag" @node-drag-start="handleNodeDragStart"
      >
        <template #default="{ node, data }">
          <div class="flex-fillRemaining align-center custom-tree-node flex">
            <span class="text-truncate" :title="node.label" style="max-width: 150px;">{{ node.label }}</span>
            <span v-if="!readonly" class="margin-left-auto tree-tools">
              <ElButton
                v-if="prevable(node)" link title="上移" :icon="Top" type="primary" style="margin-left: 8px"
                @click.stop.prevent="clickMovePrev(node)"
              />
              <ElButton
                v-if="nextable(node)" link title="下移" :icon="Bottom" type="primary" style="margin-left: 8px"
                @click.stop.prevent="clickMoveNext(node)"
              />
              <ElButton
                link title="添加子用能单元" :icon="Plus" type="primary" style="margin-left: 8px"
                @click.stop.prevent="clickAppend(data)"
              />
              <ElButton
                link title="修改" :icon="Edit" type="success" style="margin-left: 8px"
                @click.stop.prevent="clickUpdate(data)"
              />
              <ElButton
                link title="删除" :icon="Delete" type="danger" style="margin-left: 8px"
                @click.stop.prevent="clickRemove(data)"
              />
            </span>
          </div>
        </template>
      </ElTree>
    </ElScrollbar>
  </div>
</template>
